package com.ohuang.simpledatabase

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import android.widget.Toast
import com.ohuang.simpledb.DataProvider
import com.ohuang.simpledb.DataProviderTransform


class MainActivity : AppCompatActivity() {
    val tv_add:TextView by lazy{
        findViewById(R.id.tv_add)
    }
    val tv_refresh:TextView by lazy{
        findViewById(R.id.tv_refresh)
    }
    val tv_clear:TextView by lazy{
        findViewById(R.id.tv_clear)
    }
    val tv_test:TextView by lazy{
        findViewById(R.id.tv_test)
    }
    val tv_main:TextView by lazy{
        findViewById(R.id.tv_main)
    }

    val db:DataProvider<AA> by lazy {
        DataProvider<AA>(application,"bbb.db",object : DataProviderTransform<AA> {
            override fun data2String(t: AA?): String {
                return t.toString()
            }

            override fun string2data(s: String?): AA {
               return AA.json2Data(s)
            }

            override fun getKey(t: AA?): String {
                return t!!.key
            }
        })
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        tv_refresh.setOnClickListener {
            var findAll = db.findAllSortByKey()
            tv_main.setText("size=${db.size} \n")
            tv_main.append(findAll.toString())

        }
        tv_add.setOnClickListener {
            db.add(AA("5","aaaa"))
            db.add(AA("4","bbbb"))
            db.add(AA("41","aaa"))
            db.add(AA("1","ssss"))

        }
        tv_clear.setOnClickListener {
            db.deleteAll()

        }
        tv_test.setOnClickListener {

            db.update(AA("4","532424"))
        }
    }
}